package com.lucy.common.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kindear
 * 全局异常拦截处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * @全局异常处理流程
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResponseDTO<Object> exceptionHandler(Exception e){
        log.error("error:",e);
        //http 请求方式错误
        if(e instanceof HttpRequestMethodNotSupportedException){
                return ResponseDTO.wrap(HttpStatus.METHOD_NOT_ALLOWED);
        }
        // 参数类型错误
        if (e instanceof TypeMismatchException) {
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST);
        }

        // json 格式错误
        if (e instanceof HttpMessageNotReadableException) {
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST);
        }

        // 参数校验未通过
        if (e instanceof MethodArgumentNotValidException) {
            List<FieldError> fieldErrors = ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors();
            List<String> msgList = fieldErrors.stream().map(FieldError :: getDefaultMessage).collect(Collectors.toList());
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST, String.join(",", msgList));
        }

        //自定义异常
        if(e instanceof BusinessException){
            ResponseDTO<Object> res = new ResponseDTO<Object>();
            res.setCode(((BusinessException) e).getCode());
            res.setMsg(e.getMessage());
            return res;
        }
        /*
          未授权异常
         */
        if(e instanceof NotPermissionException){
            return ResponseDTO.wrap(HttpStatus.UNAUTHORIZED,e.getMessage());
        }
        /*
          未登录异常
         */
        if(e instanceof NotLoginException){
            return ResponseDTO.wrap(HttpStatus.UNAUTHORIZED,e.getMessage());
        }
        /*
          角色权限不足
         */
        if(e instanceof NotRoleException){
            return ResponseDTO.wrap(HttpStatus.UNAUTHORIZED,e.getMessage());
        }

        return ResponseDTO.wrap(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
